/**
 *    Copyright (c) 2021 WANGFEIHU
 *    SSO-PLUS is licensed under Mulan PSL v2.
 *    You can use this software according to the terms and conditions of the Mulan PSL v2.
 *    You may obtain a copy of Mulan PSL v2 at:
 *             http://license.coscl.org.cn/MulanPSL2
 *    THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *    See the Mulan PSL v2 for more details.
 */
package cn.codinglives.ssoplus.controller;



import cn.codinglives.ssoplus.entity.SsoCode;
import cn.codinglives.ssoplus.entity.SsoMain;
import cn.codinglives.ssoplus.service.JwtService;
import cn.codinglives.ssoplus.service.SsoMainService;
import cn.codinglives.ssoplus.service.ThirdCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * 用于third code 单点登录 login.
 * @author feihu.wang
 */
@Controller
public class ThirdCodeController {


    @Resource
    private SsoMainService ssoConfService;

    @Resource
    private ThirdCodeService codeService;

    @Resource
    private JwtService jwtService;

    private static final Logger LOG = LoggerFactory.getLogger(ThirdCodeController.class);


    @Value("${xforce.tenant.security.jwt.secret:888888}")
    private String defaultSecret;

    @RequestMapping(value ="/code/validation", method = RequestMethod.GET)
    public ResponseEntity validation(@RequestParam String tenantCode, @RequestParam String code) {
        String userKey = "";
        String url = "";
        List<SsoMain> ssoConfList = ssoConfService.list("code");
        for (SsoMain conf : ssoConfList) {
            if (conf.getTenantCode().equals(tenantCode)) {
                SsoCode ssoCode = ssoConfService.getSsoCodeByMainId(conf.getId());
                userKey = codeService.getUserKey(ssoCode.getUserInfoUrl(), code);
                url = conf.getSsoUrl();
            }
        }
        String accessToken = jwtService.createToken(userKey);
        url = url  + "?token=" + accessToken;
        return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(url)).build();
    }

    /**
     * use for test.
     * @param code
     * @return
     */
    @RequestMapping(value ="/code/userinfo", method = RequestMethod.GET)
    public ResponseEntity userinfo( @RequestParam String code) {
        // validate code
        return ResponseEntity.ok("wangfeihu@xforceplus.com");
    }
}
